package com.gsafety.wellsfort.service.common.impl;

import com.alibaba.fastjson.JSON;
import com.gsafety.wellsfort.common.constant.IConstant;
import com.gsafety.wellsfort.common.util.MobilePushUtil;
import com.gsafety.wellsfort.dao.push.PushInfoRecordDAO;
import com.gsafety.wellsfort.domain.dto.push.PushInfoDTO;
import com.gsafety.wellsfort.domain.dto.push.PushUtilDTO;
import com.gsafety.wellsfort.domain.model.pushRecord.PushInfoRecord;
import com.gsafety.wellsfort.domain.model.security.UserLogin;
import com.gsafety.wellsfort.service.common.IPushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: wuming
 * @Date: 2020/5/18 上午11:40
 * @Description 根据用户去推送
 */
@Slf4j
@Service
public class IPushServiceImpl implements IPushService {

    @Autowired
    PushInfoRecordDAO pushInfoRecordDAO;

    @Override
    public Boolean push(PushInfoDTO pushInfoDTO) {

        try {
            /**推送信息校验**/
            if (!Optional.ofNullable(pushInfoDTO).isPresent()) {
                return false;
            }
            log.info("调用移动推送方法参数={}", JSON.toJSONString(pushInfoDTO));
            PushUtilDTO pushUtilDTO = PushUtilDTO.builder().body(pushInfoDTO.getMessage()).
                    title(pushInfoDTO.getTitle()).deviceType(pushInfoDTO.getDeviceType()).build();


            /**根据推送用户,隔开获取推送设备ID**/
            List<String> androidList = pushInfoDTO.getUserLoginList().stream().filter(userLogin -> StringUtils.isNotBlank(userLogin.getExt2()) && userLogin.getExt2().equals("Android")).map(UserLogin::getExt3).collect(Collectors.toList());
            List<String> iosList = pushInfoDTO.getUserLoginList().stream().filter(userLogin -> StringUtils.isNotBlank(userLogin.getExt2()) && userLogin.getExt2().equals("ios")).map(UserLogin::getExt3).collect(Collectors.toList());

            /**设备id组装**/
            String androidIds = androidList.stream().collect(Collectors.joining(","));
            String iosIds = iosList.stream().collect(Collectors.joining(","));

            /**设置安卓app推送配置**/
            if (StringUtils.isNotBlank(androidIds)) {
                pushUtilDTO.setDeviceIds(androidIds);
                pushUtilDTO.setAppKey(IConstant.ANDROID_APP_KEY);
                pushUtilDTO.setDeviceType("ANDROID");
                MobilePushUtil.pushMessage(pushUtilDTO);
            }

            /**设置iosApp推送配置**/
            if (StringUtils.isNotBlank(iosIds)) {
                pushUtilDTO.setDeviceIds(iosIds);
                pushUtilDTO.setAppKey(IConstant.IOS_APP_KEY);
                pushUtilDTO.setDeviceType("iOS");
                MobilePushUtil.pushMessage(pushUtilDTO);
            }


            List<Integer> userIds = pushInfoDTO.getUserLoginList().stream().map(UserLogin::getId).collect(Collectors.toList());
            for (Integer userId : userIds) {
                PushInfoRecord pushInfoRecord = PushInfoRecord.builder().title(pushInfoDTO.getTitle()).message(pushInfoDTO.getMessage()).userIds(userId).build();
                log.info("入库数据={}", pushInfoRecord);
                this.insertRecord(pushInfoRecord);
            }
            return true;
        } catch (Exception e) {
            log.error("push功能异常={}", e);
        }
        return false;
    }

    /**
     * 获取数据
     *
     * @param userId
     * @return
     */
    @Override
    public List<PushInfoRecord> getRecord(Integer userId) {
        try {
            return pushInfoRecordDAO.getAll(userId);
        } catch (Exception e) {
            log.error("列表异常={}", e);
        }
        return null;
    }


    public int insertRecord(PushInfoRecord pushInfoRecord) {
        return pushInfoRecordDAO.insert(pushInfoRecord);
    }


    /**
     * 分割phone list
     *
     * @param list
     * @return
     */
    public Map groupList(List list) {
        int listSize = list.size();
        int toIndex = 100;
        //用map存起来新的分组后数据
        Map map = new HashMap();
        int keyToken = 0;
        for (int i = 0; i < list.size(); i += 100) {
            //最后没有100条数据剩余几条newList中就装几条
            if (i + 100 > listSize) {
                toIndex = listSize - i;
            }
            List newList = list.subList(i, i + toIndex);
            map.put("keyName" + keyToken, newList);
            keyToken++;
        }
        return map;
    }

}
